import {{javaxPackage}}.ws.rs.core.GenericType;
import {{javaxPackage}}.ws.rs.core.Response;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import {{invokerPackage}}.JSON;

{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}}
@JsonDeserialize(using={{classname}}.{{classname}}Deserializer.class)
@JsonSerialize(using = {{classname}}.{{classname}}Serializer.class)
public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}} implements {{{.}}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-implements}} {
    private static final Logger log = Logger.getLogger({{classname}}.class.getName());

    public static class {{classname}}Serializer extends StdSerializer<{{classname}}> {
        public {{classname}}Serializer(Class<{{classname}}> t) {
            super(t);
        }

        public {{classname}}Serializer() {
            this(null);
        }

        @Override
        public void serialize({{classname}} value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
            jgen.writeObject(value.getActualInstance());
        }
    }

    public static class {{classname}}Deserializer extends StdDeserializer<{{classname}}> {
        public {{classname}}Deserializer() {
            this({{classname}}.class);
        }

        public {{classname}}Deserializer(Class<?> vc) {
            super(vc);
        }

        @Override
        public {{classname}} deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            JsonNode tree = jp.readValueAsTree();

            Object deserialized = null;
            {{#discriminator}}
            Class<?> cls = JSON.getClassForElement(tree, new {{classname}}().getClass());
            if (cls != null) {
                // When the OAS schema includes a discriminator, use the discriminator value to
                // discriminate the anyOf schemas.
                // Get the discriminator mapping value to get the class.
                deserialized = tree.traverse(jp.getCodec()).readValueAs(cls);
                {{classname}} ret = new {{classname}}();
                ret.setActualInstance(deserialized);
                return ret;
            }
            {{/discriminator}}
            {{#anyOf}}
            // deserialize {{{.}}}
            try {
                deserialized = tree.traverse(jp.getCodec()).readValueAs({{{.}}}.class);
                {{classname}} ret = new {{classname}}();
                ret.setActualInstance(deserialized);
                return ret;
            } catch (Exception e) {
                // deserialization failed, continue, log to help debugging
                log.log(Level.FINER, "Input data does not match '{{classname}}'", e);
            }

            {{/anyOf}}
            throw new IOException(String.format("Failed deserialization for {{classname}}: no match found"));
        }

        /**
         * Handle deserialization of the 'null' value.
         */
        @Override
        public {{classname}} getNullValue(DeserializationContext ctxt) throws JsonMappingException {
        {{#isNullable}}
            return null;
        {{/isNullable}}
        {{^isNullable}}
            throw new JsonMappingException(ctxt.getParser(), "{{classname}} cannot be null");
        {{/isNullable}}
        }
    }

    // store a list of schema names defined in anyOf
    public static final Map<String, GenericType<?>> schemas = new HashMap<>();

    public {{classname}}() {
        super("anyOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}});
    }
{{> libraries/jersey2/additional_properties }}
    {{#additionalPropertiesType}}
    /**
     * Return true if this {{name}} object is equal to o.
     */
    @Override
    public boolean equals(Object o) {
        return super.equals(o) && Objects.equals(this.additionalProperties, (({{classname}})o).additionalProperties);
    }

    @Override
    public int hashCode() {
        return Objects.hash(getActualInstance(), isNullable(), getSchemaType(), additionalProperties);
    }
    {{/additionalPropertiesType}}
    {{#anyOf}}
    public {{classname}}({{{.}}} o) {
        super("anyOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}});
        setActualInstance(o);
    }

    {{/anyOf}}
    static {
        {{#anyOf}}
        schemas.put("{{{.}}}", new GenericType<{{{.}}}>() {
        });
        {{/anyOf}}
        JSON.registerDescendants({{classname}}.class, Collections.unmodifiableMap(schemas));
        {{#discriminator}}
        // Initialize and register the discriminator mappings.
        Map<String, Class<?>> mappings = new HashMap<>();
        {{#mappedModels}}
        mappings.put("{{mappingName}}", {{modelName}}.class);
        {{/mappedModels}}
        mappings.put("{{name}}", {{classname}}.class);
        JSON.registerDiscriminator({{classname}}.class, "{{propertyBaseName}}", mappings);
        {{/discriminator}}
    }

    @Override
    public Map<String, GenericType<?>> getSchemas() {
        return {{classname}}.schemas;
    }

    /**
     * Set the instance that matches the anyOf child schema, check
     * the instance parameter is valid against the anyOf child schemas:
     * {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}
     *
     * It could be an instance of the 'anyOf' schemas.
     * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf).
     */
    @Override
    public void setActualInstance(Object instance) {
        {{#isNullable}}
        if (instance == null) {
           super.setActualInstance(instance);
           return;
        }

        {{/isNullable}}
        {{#anyOf}}
        if (JSON.isInstanceOf({{{.}}}.class, instance, new HashSet<>())) {
            super.setActualInstance(instance);
            return;
        }

        {{/anyOf}}
        throw new RuntimeException("Invalid instance type. Must be {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}");
    }

    /**
     * Get the actual instance, which can be the following:
     * {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}
     *
     * @return The actual instance ({{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}})
     */
    @Override
    public Object getActualInstance() {
        return super.getActualInstance();
    }

    {{#anyOf}}
    /**
     * Get the actual instance of `{{{.}}}`. If the actual instance is not `{{{.}}}`,
     * the ClassCastException will be thrown.
     *
     * @return The actual instance of `{{{.}}}`
     * @throws ClassCastException if the instance is not `{{{.}}}`
     */
    public {{{.}}} get{{{.}}}() throws ClassCastException {
        return ({{{.}}})super.getActualInstance();
    }

    {{/anyOf}}
}
